﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Web.Common;
using AntUnion.FrameWork.Web.Filter;
using AntUnion.FrameWork.Web.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace AntUnion.FrameWork.Web.Controllers
{
    [EnableCors("AllowCors")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    [TypeFilter(typeof(MyExceptionFilter))]
    public class UploadController : BaseController
    {

        public UploadController()
        {
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        [HttpPost]
        [RequestSizeLimit(5242880)]
        public JsonResult UploadImage([FromForm] int? width, [FromForm] int? height)
        {
            Result res = new Result();
            try
            {
                var file = Request.Form.Files[0];
                long size = file.Length;
                if (size > 5242880)
                {
                    throw new Exception(BaseService.TOOBIG);
                }
                else
                {
                    FileData data = new FileData();
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    Image image = Image.FromStream(file.OpenReadStream());
                    string src = ImageFactory.SaveImage(image,  BaseService.PATH, fileName, width, height);
                    data.Src = src;
                    res.Data = data;
                    res.Code = 0;
                    res.Msg = "uploadSuccess";
                }
            }
            catch (Exception)
            {
                throw;
            }
            return new JsonResult(res);
        }
    }
}
